<template>
  <div class="app-container">
    <!-- 页面标题 -->
    <div class="page-header" style="margin-bottom: 20px;">
      <h2 class="page-title">
        {{ isViewMode ? '查看活动商品' : '管理活动商品' }}
      </h2>
      <div v-if="isViewMode" class="view-mode-tip">
        <el-tag type="info" size="small">查看模式 - 数据仅供查看，不可编辑</el-tag>
      </div>
    </div>
    
    <!-- 活动信息区域 -->
    <div class="activity-header">
      <!-- 有活动信息时显示表格 -->
      <el-table 
        v-if="activityInfo && activityInfo.activityName" 
        :data="[activityInfo]" 
        :show-header="true" 
        border 
        style="width: 100%; margin-bottom: 20px;"
      >
        <el-table-column label="活动名称" prop="activityName" width="200" />
        <el-table-column label="活动开始时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column label="报名截止时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.applyEndTime) }}
          </template>
        </el-table-column>
        <el-table-column label="时间段次" min-width="200">
          <template #default="scope">
            <div class="time-segments-display">
              <el-tag
                v-for="(segment, index) in timeSegments"
                :key="index"
                size="small"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ segment.timeSegment || segment }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="活动状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.activityStatus)" size="small">
              {{ getStatusText(scope.row.activityStatus) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 没有活动信息时显示提示 -->
      <div v-else class="empty-activity" style="margin-bottom: 20px;">
        <el-empty description="暂无活动信息" />
      </div>
    </div>

    <!-- 商品列表区域 -->
    <div class="products-section">
      <!-- 搜索和操作按钮 -->
      <div class="operation-bar" style="margin-bottom: 16px;">
        <el-form :model="productQueryParams" :inline="true">
<!--          <el-form-item label="商品名称">-->
<!--            <el-input-->
<!--              v-model="productQueryParams.productName"-->
<!--              placeholder="请输入商品名称"-->
<!--              clearable-->
<!--              style="width: 200px;"-->
<!--              @keyup.enter="getProductList"-->
<!--            />-->
<!--          </el-form-item>-->
                     <el-form-item>
<!--             <el-button type="primary" @click="getProductList">搜索</el-button>-->
             <el-button @click="resetProductQuery">重置</el-button>
             <el-button 
               v-if="!isViewMode" 
               type="success" 
               @click="handleAddProduct"
             >
               添加商品
             </el-button>
             <el-button 
               v-if="!isViewMode && hasNewProducts" 
               type="warning" 
               @click="handleSaveAllProducts"
               :loading="saveLoading"
             >
               保存商品
             </el-button>
             <el-button 
               v-if="!isViewMode && hasDuplicateProducts" 
               type="info" 
               @click="handleCleanDuplicateProducts"
             >
               清理重复商品
             </el-button>
           </el-form-item>
        </el-form>
      </div>

                    <!-- 商品表格 -->
       <template v-if="productsList.length > 0">
         <!-- 重复商品提示 -->
         <div v-if="!isViewMode && hasDuplicateProducts" class="duplicate-warning" style="margin-bottom: 16px;">
           <el-alert
             title="发现重复商品"
             :description="`当前列表中有重复商品，建议点击'清理重复商品'按钮进行清理`"
             type="warning"
             :closable="false"
             show-icon
           />
         </div>
         
         <el-table 
           v-loading="productLoading" 
           :data="productsList" 
           border 
           style="width: 100%"
           :row-key="(row) => row.id"
           :row-class-name="(row) => `product-row-${row.id}`"
         >
                 <el-table-column label="商品名称" min-width="200">
           <template #default="scope">
             <div style="display: flex; align-items: center; gap: 8px;">
               <span>{{ scope.row.productName || '未知商品' }}</span>
               <el-tag 
                 v-if="scope.row.isNew" 
                 type="warning" 
                 size="small"
               >
                 新添加
               </el-tag>
             </div>
           </template>
         </el-table-column>
        <el-table-column label="商品价格" width="100" align="center">
          <template #default="scope">
            <span>¥{{ scope.row.originalPrice || 0 }}</span>
          </template>
        </el-table-column>
                 <el-table-column label="库存" width="80" align="center">
           <template #default="scope">
             {{ scope.row.stockQuantity || scope.row.stock || 0 }}
           </template>
         </el-table-column>
         <el-table-column label="活动库存" width="100" align="center">
           <template #default="scope">
             <el-input
               v-if="!isViewMode"
               v-model="scope.row.activityStock"
               type="number"
               size="small"
               :placeholder="scope.row.isNew ? '设置库存 *' : '设置库存'"
               style="width: 80px;"
               @blur="handleStockBlur(scope.row)"
               @keyup.enter="handleStockBlur(scope.row)"
               :class="{ 'required-field': scope.row.isNew && (!scope.row.activityStock || scope.row.activityStock <= 0) }"
             />
             <span v-else>{{ scope.row.activityStock || 0 }}</span>
           </template>
         </el-table-column>
        <el-table-column label="活动价格" width="120" align="center">
          <template #default="scope">
            <el-input
              v-if="!isViewMode && scope.row.editingPrice"
              v-model="scope.row.tempActivityPrice"
              type="number"
              size="small"
              placeholder="请输入价格"
              style="width: 80px;"
              @blur="handlePriceBlur(scope.row)"
              @keyup.enter="handlePriceBlur(scope.row)"
              @keyup.esc="cancelPriceEdit(scope.row)"
              ref="priceInputRef"
            />
            <div v-else-if="!isViewMode" class="price-display" @click="startPriceEdit(scope.row)">
              <span v-if="scope.row.activityPrice > 0">¥{{ scope.row.activityPrice }}</span>
              <span v-else :class="scope.row.isNew ? 'text-placeholder required' : 'text-placeholder'">
                {{ scope.row.isNew ? '请设置价格 *' : '请设置价格' }}
              </span>
              <el-icon class="edit-icon"><Edit /></el-icon>
            </div>
            <span v-else>{{ scope.row.activityPrice > 0 ? `¥${scope.row.activityPrice}` : '未设置' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商家名称" width="150">
          <template #default="scope">
            {{ scope.row.storeName || '未知店铺' }}
          </template>
        </el-table-column>
                 <el-table-column label="活动场次" width="150" align="center">
           <template #default="scope">
             <el-select
               v-if="!isViewMode"
               v-model="scope.row.selectedTimeSegments"
               :placeholder="scope.row.isNew ? '请选择时间段 *' : '请选择时间段'"
               style="width: 100%;"
               @change="handleTimeSegmentChange(scope.row)"
               :class="{ 'required-field': scope.row.isNew && !scope.row.selectedTimeSegments }"
             >
               <el-option
                 v-for="(segment, index) in timeSegments"
                 :key="index"
                 :label="segment.timeSegment || segment"
                 :value="segment.timeSegment || segment"
               />
             </el-select>
             <span v-else>{{ scope.row.selectedTimeSegments || '未选择' }}</span>
           </template>
         </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="!isViewMode"
              link 
              type="primary" 
              size="small" 
              @click="handleEditProduct(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="!isViewMode"
              link 
              type="danger" 
              size="small" 
              @click="handleDeleteProduct(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
        </el-table>
      </template>
      
      <!-- 没有商品时显示提示 -->
      <template v-else>
        <div class="empty-products">
          <el-empty description="暂无商品" />
        </div>
      </template>
      
      <!-- 分页 -->
      <pagination
        v-show="productTotal > 0"
        :total="productTotal"
        v-model:page="productQueryParams.pageNum"
        v-model:limit="productQueryParams.pageSize"
        @pagination="getProductList"
        style="margin-top: 16px;"
      />
    </div>

    <!-- 选择商品弹窗 -->
    <el-dialog
      v-model="selectProductDialogVisible"
      :title="isViewMode ? '查看可选商品' : '选择商品'"
      width="80%"
      :before-close="handleCloseSelectDialog"
    >
      <!-- 搜索区域 -->
      <div class="search-area" style="margin-bottom: 20px;">
        <el-form :model="searchParams" :inline="true" label-width="68px">
          <el-form-item label="商品名称" prop="productName">
            <el-input
              v-model="searchParams.productName"
              placeholder="请输入商品名称"
              clearable
              style="width: 200px;"
              @keyup.enter="handleSearchProducts"
            />
          </el-form-item>
          <el-form-item label="商品分类" prop="categoryId">
            <el-select
              v-model="searchParams.categoryId"
              placeholder="请选择商品分类"
              clearable
              style="width: 200px;"
            >
              <el-option
                v-for="item in categoryOptions"
                :key="item.id"
                :label="item.categoryName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button 
              v-if="!isViewMode"
              type="primary" 
              icon="Search" 
              @click="handleSearchProducts"
            >
              搜索
            </el-button>
            <el-button 
              v-if="!isViewMode"
              icon="Refresh" 
              @click="resetSearchProducts"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品网格区域 -->
      <div class="product-grid" style="max-height: 400px; overflow-y: auto;">
        <div 
          class="product-item" 
          v-for="item in availableProductsList" 
          :key="item.id"
          :class="{ 'selected': selectedProducts.find(p => p.id === item.id) }"
          @click="!isViewMode ? handleSelectProduct(item) : null"
        >
          <div class="product-image">
            <img :src="item.mainImage || '/placeholder.png'" alt="商品图片" />
          </div>
          <div class="product-info">
            <div class="product-name">{{ item.productName }}</div>
            <div class="product-unit">{{ item.productParams?.unit || '个' }} {{ item.salesModel || '零售型' }}</div>
            <div class="product-price">¥{{ item.originalPrice }}</div>
          </div>
        </div>
      </div>

      <!-- 分页区域 -->
      <div v-if="!isViewMode" class="pagination-area" style="margin-top: 20px; text-align: center;">
        <el-pagination
          v-model:current-page="productPagination.currentPage"
          v-model:page-size="productPagination.pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :total="productPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleProductSizeChange"
          @current-change="handleProductCurrentChange"
        />
      </div>

      <!-- 弹框底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseSelectDialog">取消</el-button>
          <el-button 
            v-if="!isViewMode"
            type="primary" 
            @click="handleConfirmSelectProducts"
          >
            确定（已选{{ selectedProducts.length }}个商品）
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 商品编辑弹窗 -->
    <el-dialog :title="productDialogTitle" v-model="productDialogVisible" width="600px">
             <el-form ref="productFormRef" :model="productForm" :rules="productRules" label-width="100px">
         <el-form-item label="商品名称" prop="productName">
           <el-input v-model="productForm.productName" placeholder="请输入商品名称" disabled />
         </el-form-item>
         <el-form-item label="活动价格" prop="activityPrice">
           <el-input 
             v-model="productForm.activityPrice" 
             placeholder="请输入活动价格" 
             type="number"
             :disabled="isViewMode"
           />
         </el-form-item>
         <el-form-item label="活动库存" prop="activityStock">
           <el-input 
             v-model="productForm.activityStock" 
             placeholder="请输入活动库存" 
             type="number"
             :disabled="isViewMode"
           />
         </el-form-item>
         <el-form-item label="活动场次" prop="selectedTimeSegments">
           <el-select
             v-model="productForm.selectedTimeSegments"
             placeholder="请选择时间段"
             style="width: 100%;"
             :disabled="isViewMode"
           >
             <el-option
               v-for="(segment, index) in timeSegments"
               :key="index"
               :label="segment.timeSegment || segment"
               :value="segment.timeSegment || segment"
             />
           </el-select>
         </el-form-item>
       </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="productDialogVisible = false">{{ isViewMode ? '关闭' : '取消' }}</el-button>
          <el-button 
            v-if="!isViewMode"
            type="primary" 
            @click="submitProductForm"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import { 
  getActivitiess, 
  getTimeSegments,
  getActivityProducts,
  saveActivityProduct,
  deleteActivityProduct
} from "@/api/promotion/activitiess"
import { listPlatform, getPlatform } from "@/api/shangpin/platform"
import { listClassify } from "@/api/shangpin/classify"
import { listShopinfo } from "@/api/dianpu/shopinfo"

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()

// 计算是否为查看模式
const isViewMode = computed(() => {
  return route.query.mode === 'view'
})

// 计算是否有新添加的商品
const hasNewProducts = computed(() => {
  return productsList.value.some(product => product.isNew)
})

// 计算是否有重复的商品
const hasDuplicateProducts = computed(() => {
  const productIds = productsList.value.map(product => product.id)
  const uniqueIds = new Set(productIds)
  return productIds.length !== uniqueIds.size
})

// 活动信息
const activityInfo = ref({
  activityName: '',
  startTime: '',
  applyEndTime: '',
  activityStatus: 0
})
const timeSegments = ref([])

// 商品列表
const productsList = ref([])
const productLoading = ref(false)
const productTotal = ref(0)
const saveLoading = ref(false)

// 商品查询参数
const productQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  productName: '',
  activityId: null
})

// 选择商品弹窗
const selectProductDialogVisible = ref(false)
const availableProductsList = ref([])
const selectedProducts = ref([])
const categoryOptions = ref([])

// 商品搜索参数
const searchParams = reactive({
  productName: '',
  categoryId: null
})

// 商品分页
const productPagination = reactive({
  currentPage: 1,
  pageSize: 12,
  total: 0
})

// 商品编辑弹窗
const productDialogVisible = ref(false)
const productDialogTitle = ref('')
const productForm = ref({})
const productRules = reactive({
  productName: [
    { required: true, message: '商品名称不能为空', trigger: 'blur' }
  ],
  activityPrice: [
    { required: true, message: '活动价格不能为空', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式', trigger: 'blur' }
  ],
  activityStock: [
    { required: true, message: '活动库存不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '请输入正确的库存数量', trigger: 'blur' }
  ],
  selectedTimeSegments: [
    { required: true, message: '请选择活动场次', trigger: 'change' }
  ]
})

// 获取活动详情
const getActivityDetail = async () => {
  const activityId = route.query.id
  if (activityId) {
    try {
      const response = await getActivitiess(activityId)
      activityInfo.value = response.data
      
             // 获取时间段
       const timeResponse = await getTimeSegments(activityId)
       console.log('时间段API响应:', timeResponse)
       timeSegments.value = timeResponse.data || []
       console.log('解析后的时间段数据:', timeSegments.value)
       
       // 设置商品查询参数
       productQueryParams.activityId = activityId
    } catch (error) {
      ElMessage.error('获取活动详情失败')
      console.error(error)
    }
  }
}

// 获取商品列表
const getProductList = async () => {
  try {
    productLoading.value = true
    const response = await getActivityProducts(route.query.id)
    console.log('getActivityProducts API 原始响应:', response)
    
    if (response && response.data) {
      const products = response.data
      console.log('解析后的商品数据:', products)
      
      // 为每个商品获取店铺名称和设置活动场次
      for (const product of products) {
        console.log('处理商品:', product)
        console.log('商品 shopId:', product.shopId)
        
                 // 设置活动场次，使用查询到的数据
         console.log('处理商品活动场次:', {
           productId: product.id,
           productName: product.productName,
           timeSegment: product.timeSegment,
           activitySessionId: product.activitySessionId,
           availableTimeSegments: timeSegments.value
         })
         
         if (product.timeSegment) {
           product.selectedTimeSegments = product.timeSegment
           console.log('使用 timeSegment:', product.timeSegment)
         } else if (product.activitySessionId) {
           // 如果有活动场次ID，尝试从时间段列表中查找对应的值
           const timeSegment = timeSegments.value.find(ts => ts.id === product.activitySessionId)
           if (timeSegment) {
             product.selectedTimeSegments = timeSegment.timeSegment || timeSegment
             console.log('通过 activitySessionId 找到时间段:', product.selectedTimeSegments)
           } else {
             product.selectedTimeSegments = ''
             console.log('未找到对应的时间段，activitySessionId:', product.activitySessionId)
           }
         } else {
           product.selectedTimeSegments = ''
           console.log('商品没有时间段信息')
         }
         
         // 记录原始值，用于判断是否有变化
         product.originalTimeSegment = product.selectedTimeSegments
         product.originalActivityPrice = product.activityPrice || 0
         product.originalActivityStock = product.activityStock || product.stockQuantity || product.stock || 0
         
         console.log('最终设置的活动场次:', product.selectedTimeSegments)
        
        if (product.shopId) {
          try {
            const shopResponse = await listShopinfo({ id: product.shopId })
            if (shopResponse && shopResponse.rows && shopResponse.rows.length > 0) {
              product.storeName = shopResponse.rows[0].storeName
              console.log('获取到店铺名称:', product.storeName)
            }
          } catch (error) {
            console.error('获取店铺信息失败:', error)
            product.storeName = '获取失败'
          }
        } else {
          console.warn('商品缺少 shopId:', product)
          product.storeName = '未知店铺'
        }
      }
      
      productsList.value = products
      productTotal.value = products.length
      console.log('最终处理后的商品列表:', productsList.value)
    } else {
      productsList.value = []
      productTotal.value = 0
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    productsList.value = []
    productTotal.value = 0
  } finally {
    productLoading.value = false
  }
}

// 重置商品查询
const resetProductQuery = () => {
  productQueryParams.productName = ''
  getProductList()
}

// 添加商品 - 打开选择商品弹窗
const handleAddProduct = () => {
  // 查看模式下不允许添加
  if (isViewMode.value) {
    return
  }
  
  selectProductDialogVisible.value = true
  selectedProducts.value = []
  getAvailableProducts()
  getCategoryOptions()
}

// 编辑商品
const handleEditProduct = (row) => {
  // 查看模式下不允许编辑
  if (isViewMode.value) {
    return
  }
  
  productForm.value = { 
    ...row,
    activityStock: row.activityStock || row.stockQuantity || row.stock || 0,
    selectedTimeSegments: row.selectedTimeSegments || ''
  }
  productDialogTitle.value = isViewMode.value ? '查看商品' : (row.isNew ? '编辑新商品' : '编辑商品')
  productDialogVisible.value = true
}

// 删除商品
const handleDeleteProduct = async (row) => {
  // 查看模式下不允许删除
  if (isViewMode.value) {
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定删除商品"${row.productName}"吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    if (row.isNew) {
      // 如果是新添加的商品，直接从本地列表删除
      const index = productsList.value.findIndex(item => item.id === row.id)
      if (index !== -1) {
        productsList.value.splice(index, 1)
        productTotal.value = productsList.value.length
        ElMessage.success('删除成功')
      }
    } else {
      // 如果是已保存的商品，调用删除接口
      await deleteActivityProduct(row.id)
      ElMessage.success('删除成功')
      getProductList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

// 提交商品表单
const submitProductForm = async () => {
  // 查看模式下不允许提交
  if (isViewMode.value) {
    return
  }
  
  try {
    const valid = await proxy.$refs.productFormRef.validate()
    if (valid) {
             // 更新本地数据
       const productIndex = productsList.value.findIndex(item => item.id === productForm.value.id)
       if (productIndex !== -1) {
         productsList.value[productIndex].activityPrice = productForm.value.activityPrice || 0
         productsList.value[productIndex].activityStock = productForm.value.activityStock || 0
         productsList.value[productIndex].selectedTimeSegments = productForm.value.selectedTimeSegments || ''
        
        if (productsList.value[productIndex].isNew) {
          // 如果是新商品，提示用户点击保存按钮
          ElMessage.success('商品信息已更新，请点击"保存商品"按钮保存到后端')
        } else {
                     // 如果是已保存的商品，立即保存到后端
           const activityId = route.query.id
           if (activityId) {
             // 找到选中的时间段对应的ID
             const selectedTimeSegment = timeSegments.value.find(ts => 
               (ts.timeSegment || ts) === productForm.value.selectedTimeSegments
             )
             
             const productData = {
               productId: productForm.value.id,
               activityId: activityId,
               activityPrice: productForm.value.activityPrice || 0,
               activityStock: productForm.value.activityStock || 0,
               activitySessionId: selectedTimeSegment ? selectedTimeSegment.id : null
             }
             
             await saveActivityProduct(productData)
             ElMessage.success('保存成功')
           } else {
             ElMessage.error('活动ID不存在')
           }
        }
        
        productDialogVisible.value = false
      } else {
        ElMessage.error('商品不存在')
      }
    }
  } catch (error) {
    if (error !== false) { // 验证失败时error为false
      ElMessage.error('保存失败：' + error.message)
    }
  }
}

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).replace(/\//g, '-')
}

// 获取状态类型
const getStatusType = (status) => {
  const types = { 0: '', 1: 'success', 2: 'info', 3: 'danger' }
  return types[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = { 0: '新建', 1: '已开始', 2: '已结束', 3: '已关闭' }
  return texts[status] || '未知'
}

// 获取可选商品列表
const getAvailableProducts = async () => {
  const params = {
    pageNum: productPagination.currentPage,
    pageSize: productPagination.pageSize
  }
  
  // 添加搜索条件
  if (searchParams.productName && searchParams.productName.trim()) {
    params.productName = searchParams.productName.trim()
  }
  
  if (searchParams.categoryId) {
    params.categoryId = searchParams.categoryId
  }
  
  console.log('getAvailableProducts 参数:', params)
  
  try {
    const response = await listPlatform(params)
    console.log('listPlatform 响应:', response)
    
    // 统一处理响应数据格式
    if (response && response.code === 200) {
      if (response.rows) {
        // 标准分页格式
        availableProductsList.value = response.rows || []
        productPagination.total = response.total || 0
      } else if (response.data) {
        // 直接数据格式
        availableProductsList.value = Array.isArray(response.data) ? response.data : []
        productPagination.total = availableProductsList.value.length
      } else {
        availableProductsList.value = []
        productPagination.total = 0
      }
    } else if (response && response.rows) {
      // 兼容没有code字段的响应
      availableProductsList.value = response.rows || []
      productPagination.total = response.total || 0
    } else {
      availableProductsList.value = []
      productPagination.total = 0
    }
    
    console.log('availableProductsList:', availableProductsList.value)
    console.log('productPagination.total:', productPagination.total)
  } catch (error) {
    console.error('listPlatform 错误:', error)
    ElMessage.error("获取商品列表失败：" + error.message)
    availableProductsList.value = []
    productPagination.total = 0
  }
}

// 获取商品分类选项
const getCategoryOptions = async () => {
  const params = {
    pageNum: 1,
    pageSize: 1000,
    status: 'enabled'
  }
  
  console.log('getCategoryOptions 参数:', params)
  
  try {
    const response = await listClassify(params)
    console.log('listClassify 响应:', response)
    
    // 统一处理响应数据格式
    if (response && response.code === 200) {
      if (response.rows) {
        // 标准分页格式
        categoryOptions.value = response.rows || []
      } else if (response.data) {
        // 直接数据格式
        categoryOptions.value = Array.isArray(response.data) ? response.data : []
      } else {
        categoryOptions.value = []
      }
    } else if (response && response.rows) {
      // 兼容没有code字段的响应
      categoryOptions.value = response.rows || []
    } else {
      categoryOptions.value = []
    }
    
    console.log('categoryOptions:', categoryOptions.value)
  } catch (error) {
    console.error('listClassify 错误:', error)
    ElMessage.error("获取商品分类失败：" + error.message)
    categoryOptions.value = []
  }
}

// 搜索商品
const handleSearchProducts = () => {
  productPagination.currentPage = 1
  getAvailableProducts()
}

// 重置搜索
const resetSearchProducts = () => {
  searchParams.productName = ''
  searchParams.categoryId = null
  productPagination.currentPage = 1
  getAvailableProducts()
}

// 分页大小改变
const handleProductSizeChange = (size) => {
  productPagination.pageSize = size
  getAvailableProducts()
}

// 当前页改变
const handleProductCurrentChange = (page) => {
  productPagination.currentPage = page
  getAvailableProducts()
}

// 选择商品
const handleSelectProduct = (product) => {
  const index = selectedProducts.value.findIndex(item => item.id === product.id)
  if (index > -1) {
    selectedProducts.value.splice(index, 1)
  } else {
    selectedProducts.value.push(product)
  }
}

// 关闭选择商品弹窗
const handleCloseSelectDialog = () => {
  selectProductDialogVisible.value = false
  selectedProducts.value = []
}

// 确认选择商品
const handleConfirmSelectProducts = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning("请选择商品")
    return
  }
  
  const activityId = route.query.id
  if (!activityId) {
    ElMessage.error('活动ID不存在')
    return
  }
  
  let addedCount = 0
  let skippedCount = 0
  
  // 批量处理选中的商品，只添加到本地列表，不调用保存接口
  for (const product of selectedProducts.value) {
    // 检查商品是否已经存在于列表中（包括已保存的和新添加的）
    const existingIndex = productsList.value.findIndex(item => item.id === product.id)
    if (existingIndex === -1) {
      // 获取商家信息
      let storeName = '未知店铺'
      if (product.shopId) {
        // 异步获取店铺名称，但不等待结果
        listShopinfo({ id: product.shopId }).then(shopResponse => {
          if (shopResponse && shopResponse.rows && shopResponse.rows.length > 0) {
            // 更新本地列表中的店铺名称
            const productIndex = productsList.value.findIndex(item => item.id === product.id)
            if (productIndex !== -1) {
              productsList.value[productIndex].storeName = shopResponse.rows[0].storeName
            }
          }
        }).catch(error => {
          console.error('获取店铺信息失败:', error)
        })
      }
      
             // 添加到本地列表，不调用保存接口
       productsList.value.push({
         id: product.id,
         productName: product.productName,
         originalPrice: product.originalPrice, // 商品原价
         stockQuantity: product.stock, // 商品库存
         activityPrice: 0, // 活动价格需要用户自己设置
         activityStock: product.stock || 0, // 活动库存，默认等于商品库存
         selectedTimeSegments: '', // 选中的时间段，默认为空，用户需要选择
         storeName: storeName,
         shopId: product.shopId,
         editingPrice: false, // 价格编辑状态
         tempActivityPrice: undefined, // 临时价格
         isNew: true, // 标记为新添加的商品，用于保存按钮判断
         // 记录原始值
         originalActivityPrice: 0,
         originalActivityStock: product.stock || 0,
         originalTimeSegment: ''
       })
      addedCount++
    } else {
      skippedCount++
    }
  }
  
  // 更新总数
  productTotal.value = productsList.value.length
  
  // 根据添加结果显示不同的提示信息
  if (addedCount > 0 && skippedCount > 0) {
    ElMessage.success(`成功添加${addedCount}个新商品，跳过${skippedCount}个已存在的商品。请设置活动价格、活动库存和选择活动场次，然后点击"保存商品"按钮保存到后端`)
  } else if (addedCount > 0) {
    ElMessage.success(`成功添加${addedCount}个商品到列表，请设置活动价格、活动库存和选择活动场次，然后点击"保存商品"按钮保存到后端`)
  } else if (skippedCount > 0) {
    ElMessage.warning(`所有选中的商品都已存在于列表中，无需重复添加`)
  }
  
  handleCloseSelectDialog()
}

// 处理时间段选择变化
const handleTimeSegmentChange = async (row) => {
  // 查看模式下不允许编辑
  if (isViewMode.value) {
    return
  }
  
  console.log(`商品 ${row.productName} 选择的时间段:`, row.selectedTimeSegments)
  
  // 如果是新添加的商品，不立即保存到后端，等用户点击"保存商品"按钮
  if (row.isNew) {
    ElMessage.success('时间段已设置，请点击"保存商品"按钮保存到后端')
    return
  }
  
  // 如果是已保存的商品，检查是否有实际变化
  const originalTimeSegment = row.originalTimeSegment || ''
  const hasTimeSegmentChange = row.selectedTimeSegments !== originalTimeSegment
  
  if (hasTimeSegmentChange) {
    // 立即保存时间段变更
    try {
      const activityId = route.query.id
      if (activityId && row.selectedTimeSegments) {
        // 找到选中的时间段对应的ID
        const selectedTimeSegment = timeSegments.value.find(ts => 
          (ts.timeSegment || ts) === row.selectedTimeSegments
        )
        
        const productData = {
          productId: row.id,
          activityId: activityId,
          activityPrice: row.activityPrice || 0,
          activityStock: row.activityStock || row.stockQuantity || 0,
          activitySessionId: selectedTimeSegment ? selectedTimeSegment.id : null
        }
        
        await saveActivityProduct(productData)
        // 更新原始时间段记录
        row.originalTimeSegment = row.selectedTimeSegments
        ElMessage.success('时间段设置成功')
      }
    } catch (error) {
      ElMessage.error('时间段设置失败：' + error.message)
      // 恢复原始值
      row.selectedTimeSegments = originalTimeSegment
    }
  }
}

// 开始编辑活动价格
const startPriceEdit = (row) => {
  // 查看模式下不允许编辑
  if (isViewMode.value) {
    return
  }
  
  // 为每一行添加编辑状态和临时价格
  row.editingPrice = true
  row.tempActivityPrice = row.activityPrice || ''
  
  // 下一个tick后聚焦输入框
  nextTick(() => {
    // 找到当前行的价格输入框
    const currentRow = document.querySelector(`.product-row-${row.id}`)
    if (currentRow) {
      const priceInput = currentRow.querySelector('.el-input__inner')
      if (priceInput) {
        priceInput.focus()
        priceInput.select()
      }
    }
  })
}

// 处理价格输入框失焦
const handlePriceBlur = async (row) => {
  // 查看模式下不允许编辑
  if (isViewMode.value) {
    return
  }
  
  // 检查是否有实际的价格变化
  const hasPriceChange = row.tempActivityPrice !== undefined && 
                        row.tempActivityPrice !== '' && 
                        parseFloat(row.tempActivityPrice) !== (row.originalActivityPrice || 0)
  
  if (hasPriceChange) {
    const price = parseFloat(row.tempActivityPrice)
    if (isNaN(price) || price < 0) {
      ElMessage.warning('请输入有效的价格')
      row.tempActivityPrice = row.activityPrice || ''
    } else if (price === 0) {
      ElMessage.warning('活动价格不能为0')
      row.tempActivityPrice = row.activityPrice || ''
    } else {
      // 更新本地价格
      row.activityPrice = price
      
      // 如果是新添加的商品，不立即保存到后端，等用户点击"保存商品"按钮
      if (row.isNew) {
        ElMessage.success('价格已设置，请点击"保存商品"按钮保存到后端')
      } else {
        // 如果是已保存的商品，立即保存价格变更
        try {
          const activityId = route.query.id
          if (activityId) {
            // 找到选中的时间段对应的ID
            const selectedTimeSegment = timeSegments.value.find(ts => 
              (ts.timeSegment || ts) === row.selectedTimeSegments
            )
            
            const productData = {
              productId: row.id,
              activityId: activityId,
              activityPrice: price,
              activityStock: row.activityStock || row.stockQuantity || 0,
              activitySessionId: selectedTimeSegment ? selectedTimeSegment.id : null
            }
            
            await saveActivityProduct(productData)
            ElMessage.success('价格设置成功')
          } else {
            ElMessage.error('活动ID不存在')
            row.tempActivityPrice = row.activityPrice || ''
          }
        } catch (error) {
          ElMessage.error('价格保存失败：' + error.message)
          row.tempActivityPrice = row.activityPrice || ''
        }
      }
    }
  }
  
  // 退出编辑状态
  row.editingPrice = false
  row.tempActivityPrice = undefined
}

// 取消价格编辑
const cancelPriceEdit = (row) => {
  // 查看模式下不允许编辑
  if (isViewMode.value) {
    return
  }
  
  row.editingPrice = false
  row.tempActivityPrice = undefined
}

// 处理活动库存失焦
const handleStockBlur = (row) => {
  // 查看模式下不允许编辑
  if (isViewMode.value) {
    return
  }
  
  const stock = parseInt(row.activityStock)
  if (isNaN(stock) || stock < 0) {
    ElMessage.warning('请输入有效的库存数量')
    row.activityStock = row.stockQuantity || row.stock || 0
  } else if (stock > (row.stockQuantity || row.stock || 0)) {
    ElMessage.warning('活动库存不能超过商品总库存')
    row.activityStock = row.stockQuantity || row.stock || 0
  } else {
    // 检查是否有实际的库存变化
    const hasStockChange = stock !== (row.originalActivityStock || 0)
    
    // 更新本地库存
    row.activityStock = stock
    
    // 如果是新添加的商品，不立即保存到后端，等用户点击"保存商品"按钮
    if (row.isNew) {
      ElMessage.success('活动库存已设置，请点击"保存商品"按钮保存到后端')
    } else if (hasStockChange) {
      // 如果是已保存的商品且库存有变化，立即保存库存变更
      try {
        const activityId = route.query.id
        if (activityId) {
          // 找到选中的时间段对应的ID
          const selectedTimeSegment = timeSegments.value.find(ts => 
            (ts.timeSegment || ts) === row.selectedTimeSegments
          )
          
          const productData = {
            productId: row.id,
            activityId: activityId,
            activityPrice: row.activityPrice || 0,
            activityStock: stock,
            activitySessionId: selectedTimeSegment ? selectedTimeSegment.id : null
          }
          
          saveActivityProduct(productData).then(() => {
            ElMessage.success('活动库存设置成功')
          }).catch(error => {
            ElMessage.error('活动库存保存失败：' + error.message)
          })
        } else {
          ElMessage.error('活动ID不存在')
          row.activityStock = row.stockQuantity || row.stock || 0
        }
      } catch (error) {
        ElMessage.error('活动库存保存失败：' + error.message)
          row.activityStock = row.stockQuantity || row.stock || 0
      }
    }
  }
}

// 清理重复商品
const handleCleanDuplicateProducts = () => {
  // 查看模式下不允许清理
  if (isViewMode.value) {
    return
  }
  
  try {
    // 保留第一个出现的商品，删除后续重复的商品
    const seenIds = new Set()
    const uniqueProducts = []
    
    for (const product of productsList.value) {
      if (!seenIds.has(product.id)) {
        seenIds.add(product.id)
        uniqueProducts.push(product)
      } else {
        console.log(`删除重复商品: ${product.productName}`)
      }
    }
    
    const removedCount = productsList.value.length - uniqueProducts.length
    productsList.value = uniqueProducts
    productTotal.value = productsList.value.length
    
    if (removedCount > 0) {
      ElMessage.success(`成功清理${removedCount}个重复商品`)
    } else {
      ElMessage.info('没有发现重复商品')
    }
  } catch (error) {
    console.error('清理重复商品失败:', error)
    ElMessage.error('清理重复商品失败：' + error.message)
  }
}

// 保存所有新添加的商品
const handleSaveAllProducts = async () => {
  // 查看模式下不允许保存
  if (isViewMode.value) {
    return
  }
  
  const newProducts = productsList.value.filter(product => product.isNew)
  if (newProducts.length === 0) {
    ElMessage.warning('没有需要保存的商品')
    return
  }
  
  // 验证新商品是否已填写必要信息
  const invalidProducts = newProducts.filter(product => 
    !product.activityPrice || product.activityPrice <= 0 || 
    !product.activityStock || product.activityStock <= 0 || 
    !product.selectedTimeSegments
  )
  
  if (invalidProducts.length > 0) {
    ElMessage.warning(`请确保所有新商品都已设置活动价格、活动库存和选择活动场次`)
    return
  }
  
  const activityId = route.query.id
  if (!activityId) {
    ElMessage.error('活动ID不存在')
    return
  }
  
  try {
    saveLoading.value = true
    ElMessage.info(`正在保存${newProducts.length}个商品...`)
    
    // 批量保存新商品
    for (const product of newProducts) {
      try {
        // 找到选中的时间段对应的ID
        const selectedTimeSegment = timeSegments.value.find(ts => 
          (ts.timeSegment || ts) === product.selectedTimeSegments
        )
        
        const productData = {
          productId: product.id,
          activityId: activityId,
          activityPrice: product.activityPrice || 0,
          activityStock: product.activityStock || product.stockQuantity || 0,
          activitySessionId: selectedTimeSegment ? selectedTimeSegment.id : null
        }
        
        await saveActivityProduct(productData)
        
        // 保存成功后移除新商品标记
        product.isNew = false
        
        console.log(`商品 ${product.productName} 保存成功`)
      } catch (error) {
        console.error(`保存商品 ${product.productName} 失败:`, error)
        ElMessage.error(`商品 ${product.productName} 保存失败：${error.message}`)
      }
    }
    
    // 检查是否所有商品都保存成功
    const failedProducts = productsList.value.filter(product => product.isNew)
    if (failedProducts.length === 0) {
      ElMessage.success('所有商品保存成功！')
    } else {
      ElMessage.warning(`部分商品保存失败，请重试`)
    }
    
  } catch (error) {
    console.error('批量保存商品失败:', error)
    ElMessage.error('批量保存失败：' + error.message)
  } finally {
    saveLoading.value = false
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await getActivityDetail()
  // 预加载可选商品列表和分类选项
  await getAvailableProducts()
  await getCategoryOptions()
  // 获取活动详情后自动获取商品列表（确保时间段数据已加载）
  await getProductList()
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.page-header {
  .page-title {
    margin: 0 0 12px 0;
    font-size: 24px;
    font-weight: 600;
    color: #303133;
  }
  
  .view-mode-tip {
    margin-top: 8px;
  }
}

.activity-header {
  .time-segments-display {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }
}

.products-section {
  .operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.text-placeholder {
  color: #C0C4CC;
  font-style: italic;
}

.dialog-footer {
  text-align: right;
}

// 商品网格样式
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  
  .product-item {
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
    }
    
    &.selected {
      border-color: #409eff;
      background-color: #ecf5ff;
    }
    
    .product-image {
      width: 100%;
      height: 120px;
      margin-bottom: 8px;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 4px;
      }
    }
    
    .product-info {
      .product-name {
        font-size: 14px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 4px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .product-unit {
        font-size: 12px;
        color: #909399;
        margin-bottom: 4px;
      }
      
      .product-price {
        font-size: 14px;
        font-weight: 600;
        color: #e6a23c;
      }
    }
  }
}

// 表格样式优化
:deep(.el-table) {
  .el-table__header th {
    background-color: #fafafa;
    color: #606266;
    font-weight: 500;
  }
  
  .el-table__row {
    &:hover {
      background-color: #f5f7fa;
    }
  }
}

// 空状态样式
.empty-products,
.empty-activity {
  padding: 40px 0;
  text-align: center;
}

// 文本占位符样式
.text-placeholder {
  color: #c0c4cc;
  font-style: italic;
  
  &.required {
    color: #f56c6c;
  }
}

// 价格显示和编辑样式
.price-display {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: #f5f7fa;
  }
  
  .edit-icon {
    font-size: 12px;
    color: #409eff;
    opacity: 0.7;
  }
}

.price-display:hover .edit-icon {
  opacity: 1;
}

// 必填字段样式
.required-field {
  .el-input__wrapper {
    border-color: #f56c6c;
  }
  
  .el-input__inner::placeholder {
    color: #f56c6c;
  }
}
</style>